<template>
    <section>
        <a-spin :spinning="loading">
            <DetailsHeader title="创建实例" class="mb-24"></DetailsHeader>

            <div class="page-content">
                <a-form-item label="机器ID">
                    {{ machineId }}
                </a-form-item>

                <a-form-item label="地区">
                    华东
                </a-form-item>

                <a-form-item>
                    <div class="ram flex">
                        <div class="mr-8">数据盘：50GB</div>
                        <a-checkbox v-model:checked="isExpansion">需要扩容</a-checkbox>
                    </div>
                </a-form-item>

                <a-form-item label="" v-if="isExpansion">
                    <div class="expansion">
                        <a-space>
                            <a-input v-model:value="costForm.DataDisk"></a-input>
                            <span>GB</span>
                        </a-space>

                        <div class="instance-tips" style="margin-left: 24px;">
                            <InfoCircleFilled class="mr-8" />付费数据盘开机时将按 每小时¥{{ accountInfo?.runningInstanceStoragePrice
                            }}/GB进行计费，关机时 将按每小时¥{{
                                accountInfo?.stopInstanceStoragePrice }}进行计费。
                        </div>
                    </div>
                </a-form-item>

                <a-form-item>
                    <div class="ram flex">
                        <div class="mr-8">系统盘：30GB</div>
                        <a-checkbox v-model:checked="isSysExpansion"
                            v-if="userInfo?.userItem?.isEnterprise">需要扩容</a-checkbox>
                    </div>
                </a-form-item>

                <a-form-item label="" v-if="isSysExpansion">
                    <div class="expansion">
                        <a-space>
                            <a-input-number v-model:value="costForm.SystemDisk" :max="100" />
                            <span>GB</span>
                        </a-space>

                        <div class="instance-tips" style="margin-left: 24px;">
                            <InfoCircleFilled class="mr-8" />付费数据盘开机时将按 每小时<span class="fee-style">¥{{
                                accountInfo?.runningInstanceStoragePrice }}</span>/GB进行计费，关机时 将按每小时<span class="fee-style">¥{{
                                    accountInfo?.stopInstanceStoragePrice }}</span>进行计费。
                        </div>
                    </div>
                </a-form-item>

                <a-form-item label="GPU数量">

                    <a-row :gutter="24">
                        <a-col :span="8" class="gpuNum">
                            <div class="tooltip">{{ costForm.gpuNum }}</div>
                            <a-slider v-model:value="costForm.gpuNum" :marks="marks" :min="1" :max="machine.gpuNum"
                                :tooltip-visible="false"></a-slider>
                        </a-col>
                    </a-row>
                </a-form-item>

                <a-form-item>
                    <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.key === 'gpuNum'">
                                <div>{{ record.gpuNum - record.gpuUsedNum }} </div>
                            </template>
                            <template v-if="column.key === 'netUploadSpeed'">
                                <div>U: {{ unitGBS(record.netUploadSpeed) }} </div>
                                <div> D: {{ unitGBS(record.netDownloadSpeed) }}</div>
                            </template>
                            <template v-if="column.key === 'memorySize'">
                                <div>{{ printSize(record.memorySize) }} </div>
                            </template>
                            <template v-if="column.key === 'totalGlobalMem'">
                                <div>{{ printSize(record.totalGlobalMem) }} </div>
                            </template>
                            <template v-if="column.key === 'price'">
                                <div> ￥{{ record.price }} ({{ (10 * (record.discount) == 0 || 10 * (record.discount) == 10)
                                    ? '-' : 10 * (record.discount)
                                }})折</div>
                            </template>
                        </template>
                    </a-table>
                </a-form-item>

                <a-form-item label="实例镜像">
                    <a-form-item>
                        <a-radio-group v-model:value="imageType">
                            <a-radio value="1">官方镜像</a-radio>
                            <a-radio value="2">我的镜像</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-form-item v-if="imageType == 1">
                        <a-row :gutter="24">
                            <a-col :span="8">
                                <a-cascader v-model:value="costForm.image" :options="financialImageList"
                                    @change="selectImageId" placeholder="请选择框架名称/框架版本/Cuda版本/Python版本" />
                            </a-col>
                        </a-row>
                    </a-form-item>

                    <a-form-item v-if="imageType == 2">
                        <a-row :gutter="24">
                            <a-col :span="8">
                                <a-select ref="select" v-model:value="costForm.imageId" allowClear>
                                    <a-select-option v-for="item in personalImageList" :value="item.imageId">{{
                                        item.imageName
                                    }}</a-select-option>
                                </a-select>
                            </a-col>
                        </a-row>
                    </a-form-item>
                </a-form-item>

                <div class="page-global-header">
                    <div class="page-global-title">高级配置</div>
                    <a style="font-size: 14px;color: #999;" @click="expand = !expand">
                        <template v-if="expand">
                            <UpOutlined />
                        </template>
                        <template v-else>
                            <DownOutlined />
                        </template>
                    </a>
                </div>

                <div v-if="expand">
                    <a-col :span="10">
                        <a-form-item>
                            <div style="display: flex;max-width: 100%;">
                                <label style="display: flex;width: 100px;" class="item-label">
                                    <span>环境变量</span>
                                    <a-tooltip placement="top"
                                        title="添加在实例内可使用的环境变量，可以指定多个，多个环境变量分号分隔，每个环境变量使用 KEY=value 的形式定义">
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-input v-model:value="costForm.advancedConf.env"
                                    placeholder="定义环境变量，分号分割，如:FOO=bar;BAZ=tic"></a-input>
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="10">
                        <a-form-item>
                            <div style="display: flex;max-width: 100%;">
                                <label style="display: flex;width: 100px;" class="item-label">
                                    <span>入口命令</span>
                                    <a-tooltip placement="top"
                                        title='指定实例启动时执行的命令，若指定了该项，实例启动则会自动运行该选项，命令执行结果不影响实例创建。例如 "python -m http.server 8080"，则在实例启动时会直接拉起http.server模块，并监听8080端口。'>
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-input v-model:value="costForm.advancedConf.command" placeholder="#!/bin/bash"></a-input>
                            </div>
                        </a-form-item>
                    </a-col>
                </div>
            </div>

            <div class="page-bottom">
                <div class="page-bot-rg">
                    <a-button :disabled="((machine?.gpuNum - machine?.gpuUsedNum) < 1)" type="primary"
                        @click="onCreateInstance" style="display:flex;align-item:center;">
                        <svg-icon name="icon_release" style="width:20px;height:20px;margin-right: 8px;color: #ffffff;" />
                        创建实例</a-button>
                </div>
            </div>
        </a-spin>
    </section>
</template>

<script setup name="CreateInstance">
import { reactive, ref, watch, computed } from 'vue'
import { getImageList, getMyImageList, getImageId } from 'api/modules/api.gpu'
import { createInstanceApi, getMachineDetailApi } from 'api/modules/api.ownerMachine'
import { XsyMessage } from '@/libs/util.toast'
import { unitGBS, printSize } from '@/libs/util.common'
import { useRouter, useRoute } from 'vue-router'
import DetailsHeader from '@/components/common/DetailsHeader.vue'
import {
    InfoCircleFilled,
    UpOutlined,
    DownOutlined,
    QuestionCircleOutlined,
} from '@ant-design/icons-vue';
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
const useUserInfoStore = userInfoStore()
const { userInfo, accountInfo } = storeToRefs(useUserInfoStore);

const router = useRouter()
const route = useRoute();

const dataSource = ref([])
const expand = ref(false)
const isExpansion = ref(false)
const isSysExpansion = ref(false)
const machineId = route.query.machineId
const machine = ref({})
//  请求详情
const marks = reactive({
    1: 1,
})

const getDetail = () => {
    getMachineDetailApi({ machineId }).then(res => {
        if (res.code == 0) {
            dataSource.value = [res.data.list] || []
            machine.value = res.data.list || {}
            marks[machine.value.gpuNum] = machine.value.gpuNum
        }
    })
}

getDetail()

const loading = ref(false) // loading


// 获取镜像下拉列表
const imageType = ref('')
const financialImageList = ref([])
const framework = ref([])
const getFinancialImageList = () => {
    getImageList().then(res => {
        framework.value = res.data.framework
        financialImageList.value = handleData(framework.value, route.params.data?.minCudaVersion, route.params.data?.maxCudaVersion)
    })
}

// 根据条件筛选镜像ID
const selectImageId = () => {
    const [frameName, frameVer, toolVer, runtimeVer] = costForm.value.image
    const params = {
        frameName,
        frameVer,
        toolVer,
        runtimeVer
    }
    getImageId(params).then(res => {
        costForm.value.imageId = res.data.imageId
    })
}

const personalImageList = ref([])
const getPersonalImageList = () => {
    getMyImageList().then(res => {
        personalImageList.value = res.data.Images
    })
}

const handleData = (objData, minVer, maxVer) => {
    const data = { ...objData }
    const arr = []
    arr.push({ label: '框架名称', value: '框架名称', disabled: true })
    for (var i in data) {
        const obj = {}
        obj.label = i
        obj.value = i
        obj.children = []
        obj.children.push({ label: '框架版本', value: '框架版本', disabled: true })
        for (var j in data[i]) {
            const obj1 = {}
            obj1.label = j
            obj1.value = j
            obj1.children = []
            obj1.children.push({ label: 'Cuda版本', value: 'Cuda版本', disabled: true })
            for (var k in data[i][j]) {
                const obj2 = {}
                obj2.label = k
                obj2.value = k
                obj2.disabled = k < minVer || k > maxVer
                obj2.children = data[i][j][k].map(item => {
                    return {
                        label: item,
                        value: item
                    }
                })

                obj2.children.unshift({ label: 'Python版本', value: 'Python版本', disabled: true })
                obj1.children.push(obj2)

            }
            obj.children.push(obj1)
        }

        arr.push(obj)
    }

    return arr
}


getFinancialImageList()
getPersonalImageList()

const costForm = ref({
    machineId: '',
    skuName: '',
    gpuNum: 1,
    imageId: '',
    advancedConf: {
        env: '',
        command: ''
    },
    duration: 1,
    autoRenew: '',
    DataDisk: '50',
    SystemDisk: '30'
})

const onCreateInstance = () => {
    loading.value = true
    const params = {
        ...costForm.value,
        gpuNum: costForm.value.gpuNum,
        machineId,
        imageId: costForm.value.imageId
    }
    createInstanceApi(params).then(res => {
        loading.value = false
        if (res.code == 0) {
            XsyMessage.success('创建成功');
            router.push('/owner/machine')
        }
    }).catch(() => {
        loading.value = false
    })
}

const columns = [
    {
        title: 'GPU类型',
        dataIndex: 'gpuName',
        key: 'gpuName',
    },
    {
        title: '地区',
        dataIndex: 'regionName',
        key: 'regionName',
    },
    {
        title: '数量',
        dataIndex: 'gpuNum',
        key: 'gpuNum',
    },
    {
        title: '最高CUDA版本',
        dataIndex: 'maxCudaVersion',
        key: 'maxCudaVersion',
    },
    {
        title: '显存',
        dataIndex: 'totalGlobalMem',
        key: 'totalGlobalMem',
    },
    {
        title: '可租赁时间至',
        dataIndex: 'rentEndTime',
        key: 'rentEndTime',
    },
]

</script>

<style scoped lang="scss">
.page-global-header {
    display: flex;
    margin-bottom: 36px;

    .page-global-title {
        color: #223354;
        font-family: PingFang SC;
        font-size: 18px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;
        padding-right: 8px;
        margin-right: 8px;
    }

    .page-global-title::after {
        display: block;
        content: '';
        height: 5px;
        background: linear-gradient(90deg, #07F 5.32%, rgba(255, 255, 255, 0.00) 103.53%);
    }
}

.page-content {
    padding: 25px;
    background: #fff;
    padding-bottom: 158px;

    .expansion {
        display: flex;
        align-items: center;
    }

    .gpuNum {
        position: relative;

        .tooltip {
            position: absolute;
            right: 0;
            top: -10px;
            height: 20px;
            padding: 0 20px;
            border-radius: 2px;
            background: #353535;
            font-size: 12px;
            color: #fff;
            line-height: 20px;
        }
    }

}


.page-bottom {
    position: fixed;
    bottom: 0;
    background: #ffffff;
    border-radius: 2px;
    box-shadow: 0px 0px 10px 0px rgba(155, 174, 201, 0.40);
    width: calc(100% - 220px);
    padding: 24px;
    display: flex;
    justify-content: space-between;
}

.page-bot-rg {
    color: #8A93A7;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    margin-left: auto;
}

.instance-tips {
    color: #223354;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 22px;
}
</style>
